const express = require('express');
const mongo = require('../dataBase/db.js');
const router = express.Router();
const jwt = require('jsonwebtoken');
const bodyParser = require('body-parser');
const setting = require('../config/generateId');
const jsonParser = bodyParser.json();

router.post('/login', (req, res) => {
    mongo.users.findOne({ userId: req.body.userId }, (err, docu) => {
        if (err) {
            res.send({ status: false });
            return
        }
        if (docu != null) {
            if (docu.password == req.body.password) {
                let userVar = {
                    userId: req.body.userId,
                    password: req.body.password
                }
                let token = jwt.sign(userVar, userVar.userId, { expiresIn: 60 * 60 * 2 });
                res.send({ status: true, content: '登陆成功', data: { userId: userVar.userId, token: token } });
            } else {
                res.send({ status: false, content: '密码错误' });
            }
        } else {
            res.send({ status: false, content: '查无此用户' });
        }
    })
})

router.post('/register', async(req, res) => {
    let userId = setting.generateUserId(req.body.name);
    let result = await mongo.users.findOne({ userId: userId });
    if (result == null) {
        let user = {
            userId: userId,
            name: req.body.name,
            password: req.body.password,
            phoneNumber: req.body.password,
            exp: 0,
            coin: 0,
            grade: '注册会员'
        }
        new mongo.users(user).save((err, docu) => {
            if (err) throw err;
            res.send({ status: true, content: '注册成功', userId });
        })
    } else {
        res.send({ status: false, content: '请稍后重试' });
    }
})

module.exports = router;